// Copyright 2022 jeff.li. and/or its affiliates.

#include <tbir/runtime/jsonlib/json.h>

#include <turbo/json/document.h>

#include <tbir/pipeline/pickle.h>
#include <tbir/runtime/json_util.h>
#include <tbir/runtime/registry.h>

namespace tbir::runtime {

    RTValue json_loads(string_view s) {
        rapidjson::Document doc;
        JsonUtil::FromString(s, doc);
        return pickle::FromJson(doc, true);
    }

    RTValue json_load(const File &fp) {
        rapidjson::Document doc;
        // TODO(jeff): refactor JsonUtil or abandon it
        JsonUtil::FromFile(fp.path().data(), doc);
        return pickle::FromJson(doc, true);
    }

    Unicode json_dumps(const Any &obj, int indent, bool ensure_ascii) {
        rapidjson::Document doc;
        pickle::ToJson(obj, doc, doc.GetAllocator());
        if (indent == -1) {
            return JsonUtil::ToString(&doc, false, ensure_ascii).decode();
        } else {
            return JsonUtil::ToString(&doc, true, ensure_ascii, indent).decode();
        }
    }

    // RTValue json_dump(const RTValue& obj, const File& fp) {
    // TODO(jeff): Need a file class that supports write operations
    // }

    TBIR_REGISTER_GLOBAL("runtime.JsonDumps").set_body_typed(json_dumps);

}  // namespace tbir::runtime
